import ReactECharts from 'echarts-for-react';
import React from 'react';

export interface FengguPeriod {
  name?: string;
  startTime?: number;
  endTime?: number;
  label?: string;
}

interface FengguPeriodProps {
  fenggGuStateData?: FengguPeriod[];
}

function fixFloatingPoint(num: number): number {
  return parseFloat(num.toFixed(2));
}

const PeakValleyChart: React.FC<FengguPeriodProps> = ({ fenggGuStateData }) => {
  const seriesData = fenggGuStateData
    ?.map((period) => {
      const { label, startTime, endTime } = period;

      if (typeof startTime !== 'number' || typeof endTime !== 'number') {
        console.error('Invalid period data', period);
        return null;
      }

      const duration = fixFloatingPoint(endTime - startTime);
      if (duration < 0) {
        console.warn('endTime is less than startTime', period);
        return null;
      }

      return {
        name: label,
        type: 'bar',
        stack: 'total',
        data: [duration],
        itemStyle: {
          color: 'transparent',
        },
        barWidth: 30,
        show: false,
        label: {
          show: true,
          position: 'top',
          formatter: () => label,
        },
        markLine: {
          silent: true,
          symbol: ['none', 'none'],
          lineStyle: {
            type: 'solid',
            color: '#E0E0E0',
            width: 1,
          },
          label: {
            show: false,
          },
          data: [{ xAxis: startTime }, { xAxis: endTime }],
        },
      };
    })
    .filter((item) => item !== null);

  const option = {
    legend: {
      data: fenggGuStateData?.map((period) => period.label),
      show: false,
    },
    grid: {
      left: '0%',
      right: '5%',
      top: '20%',
      bottom: '35%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      min: 0,
      max: 24,
      boundaryGap: [0, 0.1],
      interval: 2,
      axisTick: { show: false },
      axisLabel: { show: false },
      splitLine: { show: false },
      show: false,
    },
    yAxis: {
      type: 'category',
      data: ['状态'],
      show: false,
    },
    series: seriesData,
  };

  return <ReactECharts option={option} style={{ height: '90px', width: '100%' }} />;
};

export default PeakValleyChart;
